﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using School.Entities;

namespace EF.WebApi.Controllers;

/// <summary>
/// 学生管理
/// </summary>
[Route("api/[controller]")]
[ApiController]
public class StudentsController : ControllerBase {
    private readonly SchoolContext _context;

    public StudentsController (SchoolContext context) {
        _context = context;
    }

    /// <summary>
    /// 获取学生列表
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Students>>> GetStudents () {
        return await _context.Students
            //.Include(x=>x.Enrollments)
            //.Where(x=>x.Id==Enrollments.)
            .ToListAsync();
    }

    /// <summary>
    /// 获取学生详情
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ActionResult<Students>> GetStudents (int id = 1) {
        var students = await _context.Students.FindAsync(id);
        if (students == null) {
            return NotFound();
        }

        return students;
    }

    /// <summary>
    /// 修改学生信息
    /// </summary>
    /// <param name="id"></param>
    /// <param name="students"></param>
    /// <returns></returns>
    [HttpPut("{id}")]
    public async Task<IActionResult> PutStudents (int id, Students students) {
        if (id != students.Id) {
            return BadRequest();
        }

        _context.Entry(students).State = EntityState.Modified;

        try {
            await _context.SaveChangesAsync();
        } catch (DbUpdateConcurrencyException) {
            if (!StudentsExists(id)) {
                return NotFound();
            } else {
                throw;
            }
        }

        return NoContent();
    }

    /// <summary>
    /// 添加学生
    /// </summary>
    /// <param name="students"></param>
    /// <returns></returns>
    [HttpPost]
    public async Task<ActionResult<Students>> PostStudents (Students students) {
        _context.Students.Add(students);
        await _context.SaveChangesAsync();

        return CreatedAtAction("GetStudents", new { id = students.Id }, students);
    }

    /// <summary>
    /// 删除学生
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteStudents (int id) {
        var students = await _context.Students.FindAsync(id);
        if (students == null) {
            return NotFound();
        }

        _context.Students.Remove(students);
        await _context.SaveChangesAsync();

        return NoContent();
    }

    /// <summary>
    /// 学生是否存在
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    private bool StudentsExists (int id) {
        return _context.Students.Any(e => e.Id == id);
    }
}
